# -*- coding: utf-8 -*-

from PyQt4.QtGui import QWidget
from PyQt4.QtCore import SIGNAL, QString, QCoreApplication, QEventLoop
from PyQt4.Qt import QRect, QDesktopWidget
from ui_mainwindow import Ui_MainWindow
from ProjectSelect import ProjectSelect
from ProjectCreate import ProjectCreate
from PrestRepo import PrestRepo
from subprocess import *
from mainfunctions import *
from cvssvn import *
from githg import *
import os

prestRepoPath = ""

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.projCreate = ProjectCreate()
        self.projCreate.browser = self.ui.textBrowser
        self.projCreate.setSelectedVCS(self.ui.vcsListCBox.currentText())        
        self.projCreate.setProjectRootUrl(str(self.ui.vcsRepoUrl.text()))
        self.projCreate.setProjectModuleUrl(str(self.ui.vcsModuleUrl.text()))
        self.projCreate.hide()
        
        self.projSelect = ProjectSelect()        
        self.projSelect.setBrowser(self.ui.textBrowser)
        self.projSelect.setSelectedVCS(self.ui.vcsListCBox.currentText())
        self.projSelect.setProjectRootUrl(str(self.ui.vcsRepoUrl.text()))
        self.projSelect.setProjectModuleUrl(str(self.ui.vcsModuleUrl.text()))
        self.projSelect.hide()

        self.prestRepo = PrestRepo()
        self.prestRepo.hide()
        
        available_geom = QDesktopWidget().availableGeometry()
        current_geom = self.frameGeometry()
        self.setGeometry(available_geom.width() / 2 - current_geom.width() / 2, available_geom.height() / 2 - current_geom.height() / 2, current_geom.width(), current_geom.height())


        self.connect(self.ui.checkOutStartBtn, SIGNAL("clicked()"), self.startCheckOut)
        self.connect(self.ui.checkOutStopBtn, SIGNAL("clicked()"), self.stopCheckOut)
	self.connect(self.ui.parseCommitLogBtn, SIGNAL("clicked()"), self.parseCommitLog)	
        self.connect(self.ui.train_testCsvBtn, SIGNAL("clicked()"), self.train_testCsvGeneration)
        self.connect(self.ui.defectMatchBtn, SIGNAL("clicked()"), self.defectMatch)
        self.connect(self.ui.prestPredictBtn, SIGNAL("clicked()"), self.prestPredict)
        self.connect(self.ui.vcsRepoUrl, SIGNAL("textChanged(const QString &)"), self.urlChanged)
        self.connect(self.ui.vcsModuleUrl, SIGNAL("textChanged(const QString &)"), self.moduleUrlChanged)
        self.connect(self.ui.vcsListCBox, SIGNAL("currentIndexChanged(const QString &)"), self.vcsChanged)

    def vcsChanged(self, currentVcs):
        self.projCreate.setSelectedVCS(str(currentVcs))
        self.projSelect.setSelectedVCS(str(currentVcs))
        if currentVcs != "Cvs":
            self.ui.label_3.setVisible(False)
            self.ui.vcsModuleUrl.setVisible(False)
        else:
            self.ui.label_3.setVisible(True)
            self.ui.vcsModuleUrl.setVisible(True)           

    def urlChanged(self, urlPath):
        self.projCreate.setProjectRootUrl(str(urlPath))
        self.projSelect.setProjectRootUrl(str(urlPath))

    def moduleUrlChanged(self, moduleUrlPath):
        self.projCreate.setProjectModuleUrl(str(moduleUrlPath))
        self.projSelect.setProjectModuleUrl(str(moduleUrlPath))        
        
    def startCheckOut(self):
        if(self.ui.vcsRepoUrl.text() == ""):
            self.ui.textBrowser.clear()
            self.ui.textBrowser.append("Enter Server Url...")
            self.ui.vcsRepoUrl.setFocus()

        else:
            self.ui.checkOutStartBtn.setEnabled(False)
            if(self.ui.vcsListCBox.currentText() == "Cvs"):
                self.ui.checkOutStopBtn.setEnabled(True)
                self.ui.textBrowser.clear()
                self.ui.textBrowser.append("<<" + self.ui.vcsListCBox.currentText() + ">> will be used as the Version Control System...")
                QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
                getCvsRepo(str(self.ui.vcsRepoUrl.text()), str(self.ui.vcsModuleUrl.text()), "projectRoot", self.ui.textBrowser)
            
            elif(self.ui.vcsListCBox.currentText() == "Git"):
                self.ui.checkOutStopBtn.setEnabled(True)
                self.ui.textBrowser.clear()
                self.ui.textBrowser.append("<<" + self.ui.vcsListCBox.currentText() + ">> will be used as the Version Control System...")
                QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
                getGitRepo(str(self.ui.vcsRepoUrl.text()), "projectRoot", self.ui.textBrowser)

            elif(self.ui.vcsListCBox.currentText() == "Mercurial"):
                self.ui.checkOutStopBtn.setEnabled(True)
                self.ui.textBrowser.clear()
                self.ui.textBrowser.append("<<" + self.ui.vcsListCBox.currentText() + ">> will be used as the Version Control System...")
                QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
                getMercurialRepo(str(self.ui.vcsRepoUrl.text()), "projectRoot", self.ui.textBrowser)

            elif(self.ui.vcsListCBox.currentText() == "Subversion"):
                self.ui.checkOutStopBtn.setEnabled(True)
                self.ui.textBrowser.clear()
                self.ui.textBrowser.append("<<" + self.ui.vcsListCBox.currentText() + ">> will be used as the Version Control System...")
                QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
                getSubversionRepo(str(self.ui.vcsRepoUrl.text()), "projectRoot", self.ui.textBrowser)

            self.ui.checkOutStopBtn.setEnabled(False)
            self.ui.parseCommitLogBtn.setEnabled(True)
        
    def stopCheckOut(self):
        self.ui.checkOutStopBtn.setEnabled(False)
        self.ui.checkOutStartBtn.setEnabled(True)
        self.ui.vcsListCBox.setFocus()
        
    def parseCommitLog(self):
        self.ui.parseCommitLogBtn.setEnabled(False)
        
        self.projCreate.listProjects1()        
        self.projCreate.exec_()

        self.ui.train_testCsvBtn.setEnabled(True)
        
    def train_testCsvGeneration(self):        
        self.ui.train_testCsvBtn.setEnabled(False)
        
        self.projSelect.listProjects2()
        self.projSelect.exec_()

        self.ui.defectMatchBtn.setEnabled(True)

    def defectMatch(self):
        self.ui.defectMatchBtn.setEnabled(False)
        
        gKeys = returnValuesforGKeys()
        generateKeys(gKeys[0], gKeys[1], gKeys[2], gKeys[3], gKeys[4], gKeys[5], self.ui.textBrowser)

        dMatch = returnValuesforDMatch()
        defectMatch(dMatch[0], dMatch[1], dMatch[2], dMatch[3], dMatch[4], dMatch[5], dMatch[6], self.ui.textBrowser)

        fMatch = returnValuesforFMatch()
        fileMatch(fMatch[0], fMatch[1], self.ui.textBrowser)

        self.ui.prestPredictBtn.setEnabled(True)
         
    def prestPredict(self):
        self.prestRepo.exec_()
        
        global prestRepoPath        
        prestRepoPath = self.prestRepo.prestRepoPath()

        if prestRepoPath != "":
            self.ui.prestPredictBtn.setEnabled(False)
            
            if(self.ui.vcsListCBox.currentText() == "Cvs"):
                if self.ui.vcsModuleUrl.text()=="":
                    tempArray = self.ui.vcsRepoUrl.text().split("/")
                    arrayLen = len(tempArray)
                    if tempArray[arrayLen-1] == "":
                        prestProjRootDir = tempArray[arrayLen-2]
                    elif tempArray[arrayLen-1] != "":
                        prestProjRootDir = tempArray[arrayLen-1]
                else:
                    tempArray = self.ui.vcsModuleUrl.text().split("/")
                    prestProjRootDir = tempArray[0]
                
            elif(self.ui.vcsListCBox.currentText() == "Subversion"):
                tempArray = self.ui.vcsRepoUrl.text().split("/")
                arrayLen = len(tempArray)
                if tempArray[arrayLen-1] == "":
                    prestProjRootDir = tempArray[arrayLen-2]
                elif tempArray[arrayLen-1] != "":
                    prestProjRootDir = tempArray[arrayLen-1]

            prestProject = returnPathforProject()
            addProject(prestProject[0], prestProjRootDir, prestRepoPath, self.ui.textBrowser)
            parseProject(prestProject[0], prestProjRootDir, prestProject[1], self.ui.textBrowser)        

            copyFilesInParseResultsFolder(prestProjRootDir, prestRepoPath)
            
            prestFileMatch(prestProjRootDir, prestRepoPath, self.ui.textBrowser)

            convertToArff(prestProjRootDir, prestRepoPath, self.ui.textBrowser)

            predictWithPrest(prestProjRootDir, prestRepoPath, self.ui.textBrowser)

            self.ui.checkOutStartBtn.setEnabled(True)

        else:
            self.ui.textBrowser.clear()
            self.ui.textBrowser.append("Enter the Prest Repo Path...")
